package models;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;

import play.data.validation.Required;
import play.db.jpa.Model;

/**
 * Community Entity, Used to create the community for each user, and it consists
 * of one user or more
 * 
 * @author Nourhan Elnehlawy
 */

@Entity
public class Community extends Model {

	/**
	 * the community's name
	 * @author Nourhan El-Nehalwy
	 */
	@Required
	public String name;

	/**
	 * community has one owner
	 * @author Nourhan El-Nehlawy
	 */
	@ManyToOne
	public User owner;
	
	@ManyToMany
	public List<User> subscribersToCommunity;

	
	/**
	 * Default constructor
	 * 
	 * @param name
	 *            the community's name
	 * @param email
	 *            the community's email
	 */
	public Community(String name, User owner) {
		this.name = name;
		this.subscribersToCommunity = new ArrayList<User>();
	    this.owner = owner;
	}
	/**
	 * this method returns a list of top 3 contributors in a community
	 *                  
	 * @return
	 *       returns the list of top contributors
	 *       @author Nourhan El-Nehlawy
	 */
	public List<User> viewListOfTopCommunityContributors(){
		List<User> topContributors = new ArrayList<User>();
		if(! this.subscribersToCommunity.isEmpty()){
			List<Long> ids = find("SELECT u.id FROM User u GROUP BY u.id ORDER BY MAX(contributionCounter) DESC").fetch(); 
   		    List<User> result = new ArrayList<User>(); 
			for (Long id : ids) result.add(User.<User> findById(id)); 
			List<User> finalResults = new ArrayList<User>();
			for(int i = 0;i < result.size();i++){
				User contributor = result.get(i);
				//System.out.println(contributor.contributionCounter);
					for(int j = 0;j < this.subscribersToCommunity.size();j++){
						if(subscribersToCommunity.get(j).id == contributor.id)
							finalResults.add(contributor);
					}
			}
			for(int i = 0;i < finalResults.size();i++)
				topContributors.add(finalResults.get(i));
		}
		return topContributors;
		
	}

	}

